import SockJS from 'sockjs-client'
import Stomp from 'webstomp-client'

let webSocket = {};
webSocket.stompClient ={};
webSocket.connection = function(configurl,subscribeurl,username,calback) {
    const socket = new SockJS(Server.serverUrl + configurl)
    this.stompClient = Stomp.over(socket)
    let that = this;
    //第一个参数，用户信息
    this.stompClient.connect({"name":username}, (frame) => {
      that.subscribe(subscribeurl,calback);
    })
};

webSocket.subscribe = function(subscribeurl,calback){
    this.stompClient.subscribe(subscribeurl, (greeting) => {
      console.log(JSON.parse(greeting.body))
      calback(JSON.parse(greeting.body));
    })
};

webSocket.sendMessage = function(sendUrl,data) {
    this.stompClient.send(sendUrl, JSON.stringify(data), {})
}

webSocket.disConnection = function(){
    if(this.stompClient){
      this.stompClient.disconnect();
    }
}

export default webSocket;
